<template>
  <el-dialog v-model="isFlowUp" title="预约随访" width="1200">
    <el-calendar v-model="calendarValue">
      <template #date-cell="{ data }">
        <div class="custom-cell">
          <!-- 默认日期显示 -->
          {{ data.day.split('-').slice(2).join('-') }}
          <!-- 日期标记 -->
          <div v-if="isDateMarked(data.day)" class="date-marker">
            <div style="font-size: 12px; color: black">已预约患者人数（人）</div>
            <div class="num" style="margin-top: 2px">{{ getNumForDate(data.day) }}</div>
            <div class="num" @click="handleViewMore(data.day)">查看更多</div>
          </div>
        </div>
      </template>
    </el-calendar>
    <el-dialog v-model="isFollow" title="查看患者随访计划" width="800">
      <avue-crud
        :data="caseData"
        :option="caseOption"
        :table-loading="tableLoading"
        v-model:page="page"
        ref="crud"
        @selection-change="selectionChange"
        @current-change="currentChange"
        @size-change="sizeChange"
      >
        <template #noticeType="{row}">
          <span v-for="(item, index) in row.noticeType.split(',')" :key="index"
              >{{ ['短信', '邮件'][Number(item) - 1] }}
              <span v-if="index + 1 != row.noticeType.split(',').length">|</span>
            </span>
        </template>
      </avue-crud>
    </el-dialog>
  </el-dialog>
</template>
<script setup>
import { useStore } from 'vuex';
import { statisticsWithMonth, listOfDate } from '@/api/visitplanrecord/visitPlanRecord';
import { ref, reactive, computed, onMounted, nextTick, watch } from 'vue';
import { ElMessage, ElMessageBox } from 'element-plus';
import { useRoute, useRouter } from 'vue-router';
const route = useRoute();
const router = useRouter();
const crud = ref(null);
const store = useStore();
const selectTab = ref(1);
const routerQuery = ref({});
routerQuery.value = route.query;

const calendarValue = ref(new Date());
let isFlowUp = ref(false);
let isFollow = ref(false);

let sendType = ref(null);
let statisticsWithMonthVal = ref([]);

let caseOption = ref({
  index: false,
  height: '400',
  // calcHeight: 330,
  // maxHeight: 300,
  tip: false,
  selection: false,
  addBtn: false,
  editBtn: false,
  viewBtn: false,
  delBtn: false,
  menu: false,
  align: 'center',
  searchShowBtn: false,
  refreshBtn: false,
  gridBtn: false,
  columnBtn: false,
  reserveSelection: true,
  column: [
    {
      label: '患者',
      prop: 'caseName',
      type: 'input',
      overHidden: true,
    },
    {
      label: '随访时间',
      prop: 'visitDate',
      type: 'input',
      overHidden: true,
    },
    {
      label: '是否通知',
      prop: 'notice',
      type: 'select',
      dicData: [
        {
          label: '是',
          value: '1',
        },
        {
          label: '否',
          value: '0',
        },
      ],
      overHidden: true,
    },
    {
      label: '通知方式',
      prop: 'noticeType',
      multiple: true,
      type: 'select',
      dicUrl: '/api/blade-system/dict-biz/dictionary?code=follow_notice_type',
      props: {
        label: 'dictValue',
        value: 'dictKey',
      },
      slot:true,
      overHidden: true,
    },
    {
      label: '通知时间',
      prop: 'noticeTime',
      multiple: true,
      type: 'select',
      dicUrl: '/api/blade-system/dict-biz/dictionary?code=follow_notice_time',
      props: {
        label: 'dictValue',
        value: 'dictKey',
      },
      overHidden: true,
    },
    {
      label: '通知内容',
      prop: 'noticeContent',
      type: 'input',
      overHidden: true,
    },
    {
      label: '状态',
      prop: 'status',
      type: 'select',
      dicUrl: '/api/blade-system/dict-biz/dictionary?code=visit_plan_record_status',
      props: {
        label: 'dictValue',
        value: 'dictKey',
      },
      overHidden: true,
      // width: 100,
    },
  ],
});
let tableLoading = ref(false);
let caseData = ref([]);
const page = ref({
  pageSize: 10,
  currentPage: 1,
  total: 4,
});
let viewMoreDay = ref(null);
let currentMonth = ref('');
/*
  type 1:基本信息入口进入
  type 2:入组管理入口进入
*/
const open = type => {
  sendType.value = type;
  isFlowUp.value = true;
  if (type === 2) {
    let today = new Date();
    let year = today.getFullYear();
    let month = today.getMonth() + 1; // getMonth() 返回的是从 0 到 11 的数字，所以需要加 1

    // 格式化月为两位数
    month = month < 10 ? '0' + month : month;

    currentMonth.value = `${year}-${month}`;
    initStatisticsWithMonth();
  }
};
// 深度监听 calendarValue
watch(
  calendarValue,
  (newValue, oldValue) => {
    currentMonth.value = formatDate(newValue).split('-').slice(0, 2).join('-');
    initStatisticsWithMonth();
  },
  { deep: true }
);

const formatDate = date => {
  let d = new Date(date);
  let year = d.getFullYear();
  let month = String(d.getMonth() + 1).padStart(2, '0');
  let day = String(d.getDate()).padStart(2, '0');

  return `${year}-${month}-${day}`;
};

const initStatisticsWithMonth = () => {
  statisticsWithMonth(routerQuery.value.trialId, currentMonth.value).then(res => {
    statisticsWithMonthVal.value = res.data.data;
  });
};
// 创建日期Set用于快速查找
const markedDates = computed(() => {
  return new Set(statisticsWithMonthVal.value.map(item => item.date));
});

// 检查当前日期是否需要标记
const isDateMarked = dateString => {
  if (sendType.value == '1') {
    return false;
  }
  return markedDates.value.has(dateString);
};

// 获取某个日期的 num 值
const getNumForDate = dateString => {
  // 在 statisticsWithMonthVal 中查找对应日期的项
  const item = statisticsWithMonthVal.value.find(item => item.date === dateString);
  return item ? item.num : 0; // 如果找到对应项，返回 num，否则返回 0
};

// 查看更多按钮点击
const handleViewMore = day => {
  isFollow.value = true;
  viewMoreDay.value = day;
  onLoad(page.value);
};

const selectionChange = list => {
  selectionList.value = list;
};
const selectionClear = () => {
  selectionList.value = [];
  crud.value.toggleSelection();
};
const currentChange = currentPage => {
  page.value.currentPage = currentPage;
  // TabRefreshChange();
  onLoad(page.value);
};
const sizeChange = pageSize => {
  page.value.pageSize = pageSize;
  // TabRefreshChange();
  onLoad(page.value);
};
const onLoad = (page, params = {}) => {
  tableLoading.value = true;

  let values = {
    descs: 'create_time',
    date: viewMoreDay.value,
    trial: routerQuery.value.trialId,
    ...params,
  };

  listOfDate(page.currentPage, page.pageSize, values).then(res => {
    const DATA = res.data.data;
    page.total = DATA.total;
    caseData.value = DATA.records;
    tableLoading.value = false;
    // selectionClear();
  });
};

defineExpose({
  open,
});
</script>
<style scoped>
.custom-cell {
  height: 100%;
  position: relative;
  display: flex;
  flex-direction: column;
  align-items: center;
}

.date-marker {
  height: 68%;
  position: absolute;
  bottom: 0;
  left: 0;
  right: 0;
  display: flex;
  flex-direction: column;
  justify-content: center;
}
.num {
  font-size: 16px;
  color: #168fd4;
  cursor: pointer;
}
</style>
